package com.xhwl.centiotdata.handler.visitor.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.base.Joiner;
import com.xhwl.centiotdata.handler.visitor.VisitorIntegrationFactory;
import com.xhwl.centiotdata.handler.visitor.VisitorIntegrationHandler;
import com.xhwl.centiotdata.pojo.constant.HaiKangYunMouConstant;
import com.xhwl.centiotdata.pojo.dto.haikangyunmou.HaiKangYunMouProject;
import com.xhwl.centiotdata.pojo.dto.haikangyunmou.HaiKangYunMouVisitors;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IAuthAccountCentService;
import com.xhwl.centiotdata.suppliersystem.haikangyunmou.HaiKangYunMouUtils;
import com.xhwl.centiotdata.suppliersystem.haikangyunmou.VisitorHaiKangYunMouHandler;
import com.xhwl.centiotdata.utils.IDCardUtils;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.cent.pedes.DeviceHaiKangDTO;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.dto.cent.visitor.VisitorInfoDTO;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.visitor.Auth;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 9:28 2022/3/4
 */
@Slf4j
@Service
public class VisitorIntegrationHaiKangYunMouHandler extends VisitorIntegrationHandler {

    @Autowired
    private VisitorHaiKangYunMouHandler visitorHaiKangYunMouHandler;
    @Autowired
    private IAuthAccountCentService authAccountCentService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IAuthAccountCentService iAuthAccountCentService;
    @Autowired
    private HaiKangYunMouUtils haiKangYunMouUtils;

    @Override
    public void afterPropertiesSet() throws Exception {
        VisitorIntegrationFactory.register(ProductEnum.HAIKANG_YUNMOU.getId(),this);
    }

    /**
     * 预约授权
     * @param configDTO
     * @param authDTO
     * @return 成功：预约id  失败：失败信息
     */
    @Override
    public ResultJson createVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO authDTO) {
        log.info("海康云眸访客创建预约授权：configDTO:{}, authDTO:{}",
                JSONObject.toJSONString(configDTO), JSONObject.toJSONString(authDTO));
        Date authStartTime = authDTO.getAuthStartTime();
        Date authEndTime = authDTO.getAuthEndTime();
        Integer intervieweeId = authDTO.getIntervieweeId();
        Integer projectId = authDTO.getProjectId();
        Integer productId = authDTO.getProductId();
        LocalDateTime start = LocalDateTimeUtil.of(authStartTime);
        LocalDateTime end = LocalDateTimeUtil.of(authEndTime);
        long days = LocalDateTimeUtil.between(start, end).toDays();
        if (days > 3 || days < 0) {
            log.error("海康云眸：离开时间和开始时间差不能超过3天: {}", projectId);
            return ResultJson.fail("离开时间和开始时间差不能超过3天");
        }

        // 被访人id（中台）
        AuthAccountMapping authAccountMapping = authAccountCentService.query(projectId, intervieweeId, productId);
        if (Objects.isNull(authAccountMapping)) {
            // 由于导入第三方人员时，productId默认为0，此处做一个兼容
            authAccountMapping = authAccountCentService.query(projectId, intervieweeId, 0);
            if (Objects.isNull(authAccountMapping) || StringUtils.isEmpty(authAccountMapping.getOpenId())){
                return ResultJson.fail("中台获取海康云眸用户id失败");
            }
        }
        String personId = authAccountMapping.getOpenId();
        // 获取roomId
        String roomId = visitorHaiKangYunMouHandler.getRoomIdByPersonId(projectId, personId,intervieweeId);
        List<String> openDeviceIdList = authDTO.getOpenDeviceIdList();
        String deviceIds;
        if (CollectionUtils.isEmpty(openDeviceIdList)) {
            deviceIds = null;
        } else {
            deviceIds = Joiner.on(",").join(openDeviceIdList);
        }
        String startTime = start.toString();
        String endTime = end.toString();

        HaiKangYunMouVisitors visitors = new HaiKangYunMouVisitors();
        visitors.setPersonId(personId);
        visitors.setPersonType(1);
        visitors.setVisitorName(authDTO.getName());
        visitors.setGender(1);
        // 访客不传身份证号，海康云眸身份默认为男
        if (!StringUtils.isEmpty(authDTO.getIdentityCard())){
            visitors.setGender(IDCardUtils.getGender(authDTO.getIdentityCard()));
        }
        visitors.setPhone(authDTO.getPhone());
        visitors.setRoomId(roomId);
        visitors.setVisitReason(authDTO.getSubjectMatter());
        visitors.setVisitorEffectiveTime(startTime);
        visitors.setVisitorLeaveTime(endTime);
        visitors.setDeviceIds(deviceIds);
        visitors.setOpenTimes(9);
        String visitorCode;
        try {
            visitorCode = visitorHaiKangYunMouHandler.createVisitorAuth(configDTO.getProjectId(), visitors);
        } catch (Exception e) {
            log.error("海康云眸预约授权失败: {}", e.getMessage());
            return ResultJson.fail("海康云眸预约授权失败：" + e);
        }
        return ResultJson.success(visitorCode);
    }

    @Override
    public ResultJson removeVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorInfoDTO infoDTO) {
        log.info("海康云眸访客取消预约授权：configDTO:{}, infoDTO:{}",
                JSONObject.toJSONString(configDTO), JSONObject.toJSONString(infoDTO));
        String openId = iAuthAccountCentService.queryOpenId(infoDTO.getProjectId(),infoDTO.getIntervieweeId(),null,configDTO.getProductId());
        log.info("获取的openid为{}",openId);
        try {
            visitorHaiKangYunMouHandler.deleteVisitorAuth(configDTO.getProjectId(), openId);
        } catch (Exception e) {
            log.error("海康云眸访客删除失败: {}", e.getMessage());
            return ResultJson.fail("海康云眸访客删除失败：" + e.toString());
        }
        return ResultJson.success();
    }

    @Override
    public ResultJson getQrCode(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        log.info("海康云眸访客获取二维码：configDTO:{}, visitorAuthDTO:{}",
                JSONObject.toJSONString(configDTO), JSONObject.toJSONString(visitorAuthDTO));
        String reservationId = visitorAuthDTO.getOpenId();
        String qr = (String) redisUtils.get(HaiKangYunMouConstant.QR + reservationId);
        log.info("海康预约二维码:{}",qr);
        if (qr == null) {
            return ResultJson.fail("二维码已经过期");
        }
        return ResultJson.success(qr);
    }

    @Override
    public ResultJson<List<Auth>> getAuthDeviceListByOpenId(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO){
        log.info("海康云眸访客获取人员门禁设备信息：configDTO:{}, visitorAuthDTO:{}",
                JSONObject.toJSONString(configDTO), JSONObject.toJSONString(visitorAuthDTO));
        String openId = iAuthAccountCentService.queryOpenId(configDTO.getProjectId(),visitorAuthDTO.getIntervieweeId(),null,configDTO.getProductId());
        if (StringUtils.isEmpty(openId)){
            openId = iAuthAccountCentService.queryOpenId(configDTO.getProjectId(),visitorAuthDTO.getIntervieweeId(),null,0);
            if (StringUtils.isEmpty(openId)){
                log.error("人员没有同步第三方");
                return ResultJson.fail("人员没有同步到第三方");
            }
        }
        List<HaiKangYunMouProject> yunMouBuildings = haiKangYunMouUtils.getDefaultYunMouConfigByProjectId(configDTO.getProjectId(),visitorAuthDTO.getIntervieweeId());
        List<DeviceHaiKangDTO> deviceHaiKangDTOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(yunMouBuildings)){
            String finalOpenId = openId;
            yunMouBuildings.forEach(yunMouBuilding -> {
                deviceHaiKangDTOS.addAll(visitorHaiKangYunMouHandler.getAuthDeviceList(finalOpenId,yunMouBuilding.getCommunityId(),configDTO));
            });
        }

        log.error("获取的门禁权限{}",deviceHaiKangDTOS);
        List<Auth> authList = new ArrayList<>();
        for (DeviceHaiKangDTO deviceHaiKangDTO : deviceHaiKangDTOS) {
            Auth authDto = new Auth();
            authDto.setAuthName(deviceHaiKangDTO.getDeviceName());
            authDto.setAuthType(1);
            authList.add(authDto);
        }
        return ResultJson.success(authList);
    }
}
